<?php

namespace App\Model\Admins;

use App\Model\BaseModel;
use App\Utility\Token;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Http\Session\Session;

class AdminsModel extends BaseModel{

    protected $table = 'admins';

    /**
     * 分页
     * @param int $page
     * @param array $where
     * @param string $columns
     * @param null $perPage
     * @return array
     */
    public function paginate(int $page = 1,$where = [], $columns = '*', $perPage = null) {

        $perPage = $perPage ?: $this->getPerPage();
        if(count($where)){
            if($where['username']){
                $this->db->whereLike('username','%'.$where['username'].'%');
            }
            if($where['nickname']){
                $this->db->whereLike('nickname','%'.$where['nickname'].'%');
            }
        }
        $data = $this->db->withTotalCount()
            ->orderBy('id', 'DESC')
            ->get($this->table, [($page - 1) * $perPage, $perPage], $columns);
        $total = $this->db->getTotalCount();
        $result = [
            'data' => $data,
            'total' => $total,
            'last_page'=>ceil($total/$perPage),
            'per_page'=>$perPage,
            'current_page'=>$page,
        ];
        return $result;
    }

    /**
     * 根据主键ID查询一条数据
     * @param AdminsBean $bean
     * @param string $columns
     * @return AdminsBean|null
     */
    public function find(AdminsBean $bean, $columns = '*'):?AdminsBean {
        $data = $this->db->where('id', $bean->getId())->getOne($this->table,$columns);
        return empty($data) ? null : new AdminsBean($data);
    }

    /**
     * 判断用户
     * @param AdminsBean $bean
     * @return bool
     */
    public function check(AdminsBean $bean){
        //password_verify($bean->getPassword())
        $user = $this->db->where('username', $bean->getUsername())->getOne($this->table);
        if(empty($user)){
            return false;
        }
        $user = new AdminsBean($user);
        if(password_verify($bean->getPassword(),$user->getPassword())){
            return true;
        }
        return false;
    }

    /**
     * 获取登陆用户信息
     * @param AdminsBean $bean
     * @return bool
     */
    public function user($token){
        $username = Token::sessionCheckToken($token);
        if($username === false){
            return false;
        }
        $user = new AdminsBean(['username'=> $username]);
        $data = $this->db->where('username', $user->getUsername())->getOne($this->table);
        $result = empty($data) ? null : (new AdminsBean($data))->toArray();
        unset($result['password']);
        return $result;
    }












}
